package kr.co.sdworld.api.apns.service;

import javapns.Push;
import javapns.notification.PushNotificationPayload;
import javapns.notification.PushedNotification;
import javapns.notification.PushedNotifications;
import javapns.notification.ResponsePacket;
import kr.co.sdworld.api.apns.model.ApnsCert;
import kr.co.sdworld.api.apns.model.ApnsMessage;
import kr.co.sdworld.api.apns.repository.cert.ApnsCertDao;
import kr.co.sdworld.api.apns.repository.message.ApnsMessageDao;
import kr.co.sdworld.stone.SpringBeanUtil;
import kr.co.sdworld.webs.ServiceContext;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

@Service
public class PushServiceImpl implements PushService
{
	private Logger logger = Logger.getLogger( getClass());

	@Override
	public void push( String deviceToken, String appId, String message, String sound)
	{
		ApnsMessage apnsMessage = new ApnsMessage();
		synchronized ( apnsMessage)
		{

			ApnsMessage latestMessage = SpringBeanUtil.repository( ApnsMessageDao.class).getLatestApnsMessageByMaxBadge( appId);

			ApnsCert cert = SpringBeanUtil.repository( ApnsCertDao.class).getApnsCert( appId);

			int badge = latestMessage.getBadge() + 1;
			apnsMessage.setAppId( appId);
			apnsMessage.setBadge( badge);
			apnsMessage.setSound( sound);
			apnsMessage.setMessage( message);

			SpringBeanUtil.repository( ApnsMessageDao.class).create( apnsMessage);

			pushToApns( deviceToken, cert.getCertPass(), cert.getCertPath(), message, badge, sound);
		}
	}

	private void pushToApns( String deviceToken, String certPass, String certPath, String message, int badge, String sound)
	{
		try
		{
			String certificatePath = ServiceContext.getSession().getServletContext().getRealPath( certPath);
			PushNotificationPayload payLoad = PushNotificationPayload.complex();
			payLoad.addAlert( message);
			payLoad.addBadge( badge);
			payLoad.addSound( sound); // default

			PushedNotifications notifications = Push.payload( payLoad, certificatePath, certPass, false, deviceToken);
			PushedNotification pushed = notifications.firstElement();
			boolean isSuccess = pushed.isSuccessful();
			if ( !isSuccess)
			{
				ResponsePacket rp = pushed.getResponse();
				if ( rp != null)
				{
					System.out.println( "response-message : " + rp.getMessage());
				}

				Exception pe = pushed.getException();
				if ( pe != null)
				{
					pe.printStackTrace();
				}
			}

			if ( !isSuccess)
			{
				throw new RuntimeException( "Error!!");
			}
		} catch ( Exception e)
		{
			logger.error( "Error!! while push message..", e);
			throw new RuntimeException( e);
		}
	}
}
